<template>
    <div>
        <el-dialog class="dialog-modal yzimport-dialog" title="导入数据" :visible.sync="dialogVisible" width="60%"
            append-to-body destroy-on-close>
            <div class="mb-2">
                <div class="mb-2">
                    <div class="flexList">
                        <div style="margin-right:10px; line-height: 1;">第一步：请先上传文件</div>
                        <el-button type="text" @click="downloadModule()" icon="far fa-file-download">
                            点击下载dbf模板
                        </el-button>
                        <el-button type="text" icon="far fa-file-download" @click="downloadModuleExcel()">
                            点击下载excel模板
                        </el-button>
                        <el-button icon="far fa-file-download" type="text" @click="downFieldExplain()">
                            点击下载上传字段说明
                        </el-button>
                    </div>
                    <div class="flexList mt-2">
                        <el-upload class="upload-demo" action="" :auto-upload="false" :on-change="uploadFile"
                            :accept="uploadLimit.ext">
                            <el-button size="mini" plain class="flexList h30" icon="far fa-cloud-upload"
                                style="width: 110px">上传文件
                            </el-button>

                            <div slot="tip" style="color:var(--danger-color);margin-top: 7px;">
                                支持上传{{ uploadLimit.ext }}文件，且不超过{{
                                    uploadLimit.size / 1024 / 1024
                                }}M
                            </div>

                        </el-upload>
                    </div>
                </div>
                <div>
                    <div class="mb-2 flexList">
                        <div class="text-dark">第二步：匹配需上传的字段</div>
                        <el-button type="primary" size="mini" class="ml-2" v-show="isShowQueRen" @click="showMatch">
                            <span v-if="isShowMatch">收起字段</span>
                            <span v-else>展开字段</span>
                        </el-button>
                        <el-tag type="warning" class="ml-3" v-if="mustArry.length > 0">提示：<span
                                class="text-danger font-size-16 mr-2 mt-2">
                                *</span>为必传字段必须选中，且值不得为空，否则将影响上传或其他业务功能，导入前请先确认。
                        </el-tag>
                    </div>
                    <div style="max-height: 500px; overflow-y: auto" v-show="isShowMatch">
                        <importFields :module="module" :excelFields="excelFields" :dbFields="dbFields"
                            :ChooseFields="dbChooseFields" @dbChange="
                                dbChooseFields = $event;
                            $forceUpdate();
                            " :mustArry="mustArry" v-model="excelForm" @change="change" class="mb-2">
                        </importFields>

                    </div>
                    <div class="mb-2 flexList">
                        <div class="text-dark">第三步：校验需上传的数据</div>
                        <el-button type="primary" size="mini" class="ml-2" @click="showQueRen">确认字段</el-button>
                        <span v-show="isShowQueRen" class="ml-2">已读取<span class="text-danger">{{ readLength }}</span>条数据
                            <span class="text-success"> 共{{ totalLength }}条 </span>
                            <span class="text-danger"> 错误{{ badRows }}条 </span>
                            <span class="text-info">共{{ (fileSize / 1024 / 1024).toFixed(2) }}M</span>
                        </span>
                    </div>

                    <div style="max-height: 400px; overflow-y: auto">
                        <importPreView ref="importPreView" :list="excelList" :bounds="bounds" :dbFields="dbChooseFields"
                            v-show="isShowQueRen" :badList="badList">
                        </importPreView>
                        <!--          数据类型错误展示-->
                        <table class="table light-table table-hover table-bordered " v-if="isShowTypeError">
                            <thead class="thead-light">
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型错误信息</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(value, key) in typeError">
                                    <td>{{ key }}</td>
                                    <td>{{ value }}</td>
                                </tr>
                            </tbody>
                        </table>
                        <!--          数据类型错误展示结束-->
                    </div>
                </div>
                <div class="text-center mt-2" v-if="isShowQueRen">

                    <div v-if="!isShowDete && !hasBad">
                        <el-button type="primary" size="medium" @click="sureImport()">确认并导入</el-button>
                    </div>
                    <div v-else-if="hasBad">
                        <el-button type="primary" size="medium" @click="sureImport()">忽略错误继续导入</el-button>
                        <el-button type="info" size="medium" @click="hide()">取消导入</el-button>
                    </div>
                    <div v-else>
                        <el-button type="primary" size="medium" @click="downError" class="mr-2">下载错误数据</el-button>
                        <el-button type="info" size="medium" @click="deleteFile">删除已上传</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import importFields from "./ImportComponents/importFields.vue";
import importPreView from "./ImportComponents/importPreView.vue";
import { getLimit, importFileCustom, importFileSure, deleteUpload } from "@/api/public";
import { getToken } from '@/utils/auth' // get token from cookie

export default {
    components: {
        importFields,
        importPreView,
    },
    model: {
        event: "input",
        data: "form",
    },
    props: {
        importConfig: Object,
    },
    data() {
        return {
            dialogVisible: false,
            excelForm: {},
            excelFields: [],
            bounds: {},
            sureList: [],
            excelList: [],
            badList: [],
            dbFields: [],
            module: "",
            dbChooseFields: [],
            isShowQueRen: false,
            isShowMatch: true,
            hasSelect: false,
            uploadLimit: {
                size: '',
                exit: ''
            },
            fileSize: "",
            isShowDete: false, //显示撤销上传和下载错误数据
            fileId: "",
            fileList: [],
            rollBackKey: "", //撤销key
            totalLength: "", //总条数
            readLength: "", //已读取
            importLength: "", //成功导入
            mustArry: [],
            success: null,
            hasBad: false,
            badRows: "",
            isShowTypeError: false,
            importFields: []
        }
    },
    methods: {
        checkFile(_this, size, ext, file) {
            if (size < file.size) {
                _this.$notify.warning({
                    message: "只能上传" + size / 1024 / 1024 + "M以内文件"
                });
                return false;
            }
            var fileExt = file.name.split(".")[file.name.split(".").length - 1];

            if (ext.indexOf(fileExt) == -1) {
                _this.$notify.warning({
                    message: "上传文件类型错误"
                });
                return false;
            }
            return true;
        },
        async initImportShow(conf) {
            await this.getFileLimit();

            if (conf.success) {
                this.success = conf.success;
            }
            this.dialogVisible = true;
            this.isShowQueRen = false;
            this.isShowMatch = true;
            this.form = {};
            this.fileId = "";
            this.excelList = [];
            this.excelFields = [];
            this.dbChooseFields = [];
            this.dbFields = [];
            this.mustArry = [];
            this.excelForm = {};
            this.isShowTypeError = false;
            this.typeError = {};

        },
        hide() {
            this.dialogVisible = false;
        },
        change(e) {
            this.hasSelect = true;
            this.bounds = e;
            this.$refs.importPreView.refresh(e);
            this.$emit("change", e);
        },
        uploadFile(file, fileList) {
            var _this = this;
            if (
                this.checkFile(_this, this.uploadLimit.size, this.uploadLimit.ext, file.raw)
            ) {
                let upParams = {
                    module: "Import",
                    templateCode: this.module,
                };
                importFileCustom(file.raw, upParams).then((res) => {


                    if (fileList.length > 1) {
                        fileList.splice(0, 1);
                    }
                    let newData = res.data;
                    // console.log(newData)
                    this.excelForm = {};
                    this.fileId = newData.file.fileId;
                    this.importFields = newData.fields;
                    this.dbFields = newData.templateKey;
                    this.totalLength = newData.dataCount;
                    this.readLength = newData.dataSize;
                    this.fileSize = newData.file.size; //上传大小
                    let datalist = [];
                    newData.dataList.forEach((x) => {
                        //大小写不区分
                        x = this.toLower(x);
                        datalist.push(x);
                    });
                    this.excelList = datalist;

                    let newArry = [];
                    this.excelFields = [];
                    this.dbFields.forEach((i) => {
                        this.excelFields.push(i.columnName)

                        //自动匹配

                        const isEnglish = this.excelFields.find(d => d.toLowerCase() == i.dbColumnName.toLowerCase())
                        const isChinese = this.excelFields.find(d => d == i.dbColumnMemo)

                        if (isEnglish) {
                            this.excelForm[i.dbColumnName] = i.dbColumnName
                        } else if (isChinese) {
                            this.excelForm[i.dbColumnName] = i.dbColumnMemo
                        } else {
                            this.excelForm[i.dbColumnName] = ""
                        }

                        if (i.mustImport) {
                            newArry.push(i.dbColumnName);
                        }
                    });
                    this.mustArry = newArry;


                    this.$nextTick(() => {
                        this.dbChooseFields = JSON.parse(JSON.stringify(this.dbFields));
                        this.change(this.excelForm);
                        this.isShowMatch = true;
                        this.isShowDete = false;
                    });

                });
            }
        },
        showQueRen() {
            this.isShowQueRen = true;
            this.isShowMatch = false;
            let fileObj = {
                param: {},
                keyMap: {},
            };

            this.dbChooseFields.forEach((k) => {
                fileObj.keyMap[k.dbColumnName] = this.importFields.filter((v) => {
                    return k.columnName == v || k.columnNameZh == v;
                })[0];
            });
            this.$refs.importPreView.refresh(fileObj.keyMap);
            importFileSure(this.fileId, this.module, true,
                fileObj).then((res) => {
                    if (res.data.status == "error") {
                        this.isShowQueRen = false;
                        this.isShowMatch = true;
                        this.isShowTypeError = true;

                        this.typeError = res.data.typeError;
                        return;
                    }
                    this.isShowTypeError = false;
                    let badList = [];
                    this.badRows = res.data.badRows
                    res.data.badList.forEach((x) => {
                        //大小写不区分
                        x = this.toLower(x);
                        badList.push(x);
                    });
                    this.badList = badList;
                    if (this.badList.length) {
                        this.hasBad = true
                    }
                })
        },
        showMatch() {
            this.isShowMatch = !this.isShowMatch;
        },
        toLower(obj) {
            for (var k in obj) {
                obj[k.toLowerCase()] = obj[k];
                if (k.toLowerCase() != k) {
                    delete obj[k];
                }
            }
            return obj;
        },

        sureImportReal() {
            let fileObj = {
                param: {},
                keyMap: {},
            };

            this.dbChooseFields.forEach((k) => {
                fileObj.keyMap[k.dbColumnName] = this.importFields.filter((v) => {
                    return k.columnName == v || k.columnNameZh == v;
                })[0];
            });

            let sync = true;
            this.$confirm("是否确认导入数据?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                if (this.fileId) {
                    importFileSure(this.fileId, this.module, false, fileObj).then((res) => {

                        if (res.data) {

                            let statusData = res.data;
                            this.rollBackKey = statusData.rollBackKey;
                            this.importLength = statusData.successRows;
                            if (statusData.checkStatus != "no") {
                                if (statusData.checkStatus != "success") {
                                    this.$message({
                                        type: "warning",
                                        message: statusData.checkMsg
                                            ? statusData.checkMsg
                                            : "请下载错误数据并重新上传!",
                                    });
                                    this.isShowDete = true;
                                    return;
                                } else {
                                    sync = false;
                                    this.exportFinal();
                                    this.hide();
                                }
                            }
                        }
                        if (this.importLength) {
                            this.$emit('success')
                            this.$notify({
                                type: "success",
                                message: "已成功导入" + this.importLength + "条数据!",
                                duration: 3000,
                            });
                        } else {
                            this.$notify({
                                type: "success",
                                message: res.message,
                                duration: 3000,
                            });
                        }

                        this.hide();
                        if (this.success && sync) {
                            this.success();
                        }
                    });
                } else {
                    this.$message({
                        type: "warning",
                        message: "暂无可导入数据",
                    });
                }
            })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消导入",
                    });
                });
        },
        sureImport() {

            if (this.importConfig.passCheck) {
                this.$emit('passcheck', this.sureImportReal)
            } else {
                this.sureImportReal();
            }

        },

        // 导入正式表
        exportFinal() {
            let formData = {};
            formData.templateCode = this.module;
            formData.rollBackKey = this.rollBackKey;
            exportSubmit(formData).then((res) => {
                if (res.status) {
                    if (this.success) {
                        this.success();
                    }
                }
            });
        },
        // 删除上传文件
        deleteFile() {
            this.$confirm("确定撤销刚才的导入?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                deleteUpload(this.rollBackKey).then((res) => {
                    this.$message({
                        type: "success",
                        message: "数据撤销成功!",
                    });
                });
            }).catch(() => {
                this.$message({
                    type: "info",
                    message: "已取消",
                });
            });
        },
        // 下载错误数据
        downError() {
            let url;
            url = "/yethan/ImportExport/downCheckList?templateCode=" +
                this.module +
                "&ytoken=" +
                getToken()

            window.location.href = url;
        },
        // 下载模板
        downloadModule() {
            let url;
            url =
                "/yethan/ImportExport/downloadTemplate/" +
                this.module +
                "?ytoken=" +
                getToken()
            window.location.href = url;
        },
        downloadModuleExcel() {
            let url;
            url =
                "/yethan/ImportExport/downloadTemplateExcel/" +
                this.module +
                "?ytoken=" +
                getToken()


            window.location.href = url;
        },
        // 字段说明
        downFieldExplain() {
            let url;
            url =
                "/yethan/ImportExport/downFieldExplain/" +
                this.module +
                "?ytoken=" +
                getToken()


            window.location.href = url;
        },
        // 获取上传参数限制
        getFileLimit() {
            getLimit("Import").then(res => {
                this.uploadLimit["ext"] = "." + res.data.fileUploadExtLimit.replaceAll(",", ",.");
                this.uploadLimit["size"] = res.data.fileUploadMaxSize;
            })
        },
    },
    watch: {
        "importConfig.module": {
            immediate: true,
            handler(e) {
                this.module = e
            }
        },
        form: {
            deep: true,
            handler(e) {
                this.$emit("change", e)
            }
        }
    }
}
</script>

<style lang="scss">
.yzimport-dialog .el-dialog__header {
    border-bottom: 1px solid #DFDFDF;
}

.yzimport-dialog .mb-2 {
    margin-bottom: .5rem !important;
}

.yzimport-dialog .flexList {
    display: flex;
    align-items: center;
}

.yzimport-dialog .ml-2,
.yzimport-dialog .mx-2 {
    margin-left: 0.5rem !important;
}

.yzimport-dialog .msgContent {
    flex-wrap: wrap;
    border-right: 1px solid #dfdfdf;
    border-bottom: 1px solid #dfdfdf;
    gap: 1px;
    background: #ebebeb;
}

.yzimport-dialog .filedName {
    border-left: 1px solid #DFDFDF;
    overflow: hidden;
    text-overflow: ellipsis;
    background-color: #F3F5FB;
    height: 100%;
    padding-left: 5px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.yzimport-dialog .msgLabel,
.yzexport-dialog .msgLabel {
    height: 45px;
    display: flex;
    align-items: center;
    background: #fff;
}

.yzimport-dialog .msgVal {
    background-color: #fff;
}

.yzimport-dialog .w-100 {
    width: 100% !important;
}

.yzimport-dialog .col-sm-1 {
    flex: 1;
}

.yzimport-dialog .col-sm-2 {
    flex: 2;
}

.yzimport-dialog .col-sm-3 {
    flex: 3;
}

.yzimport-dialog .col-sm-6 {
    flex: 4;
}

.yzimport-dialog .table>thead {
    vertical-align: bottom;
}

.yzimport-dialog .table>:not(:last-child)>:last-child>* {
    border-bottom-color: #eff0f2;
}


.yzimport-dialog .light-table .thead-light th {
    background-color: #F3F5FB;
}

.yzimport-dialog .table th,
.table td {
    height: 35px;
    box-sizing: border-box;
}

.yzimport-dialog .table> :not(caption)>*>* {
    padding: 0.5rem;
}

.yzimport-dialog .table-bordered {
    border: 1px solid #eff0f2;
}

.yzimport-dialog .import-tabs.el-tabs--border-card>.el-tabs__content {
    padding: 0;
}

.yzimport-dialog .table {
    --bs-table-bg: transparent;
    --bs-table-accent-bg: transparent;
    --bs-table-striped-color: #495057;
    --bs-table-striped-bg: #f8f9fa;
    --bs-table-active-color: #495057;
    --bs-table-active-bg: rgba(0, 0, 0, 0.1);
    --bs-table-hover-color: #495057;
    --bs-table-hover-bg: #f8f9fa;
    width: 100%;
    margin-bottom: 1rem;
    color: #495057;
    vertical-align: top;
}

.yzimport-dialog .export-tip {
    background-color: #F3F5FB;
}

.yzimport-dialog .field_intro {
    width: 215px;
    height: 40px;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.yzimport-dialog .border-gray {
    border: 1px solid #DFDFDF;
}

.yzimport-dialog .text-center {
    text-align: center !important;
}

.yzimport-dialog .pl-2,
.px-2 {
    padding-left: 0.5rem !important;
}

.yzimport-dialog .p-2 {
    padding: .5rem !important;
}


.yzexport-dialog .el-dialog__body {
    padding-top: 0;
}
</style>